package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.to.es.SkuHasStockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq(WareSkuEntity::getSkuId, skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq(WareSkuEntity::getWareId, wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        // 新建集合用于组装
        ArrayList<SkuHasStockVo> emptyList = new ArrayList<>();
        // 一次查出所有符合skuId的库存信息
//        List<WareSkuEntity> skuEntityList = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuIds));
        List<WareSkuEntity> skuEntityList = baseMapper.selectBatchIds(skuIds);
        // 根据SkuHasStockVo::getSkuId分组，组装SkuHasStockVo数组
        Map<Long, List<SkuHasStockVo>> collect = skuEntityList.stream()
                .map(item -> {
                    SkuHasStockVo vo = new SkuHasStockVo();
                    vo.setSkuId(item.getSkuId());
                    vo.setHasStock((item.getStock() - item.getStockLocked()) > 0 ? true : false);
                    return vo;
                }).collect(Collectors.groupingBy(SkuHasStockVo::getSkuId, Collectors.toList()));

        // 将collect中的value取出来放在emptyList中
        collect.forEach((skuId, list)->{
            emptyList.addAll(list);
            System.out.println(list);
            System.out.println("---");
        });
        return emptyList;
    }

}